package com.mvc.business.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.ProjectUtils;
import com.mvc.business.model.Order;
import com.mvc.business.model.Purchase;
import com.mvc.component.mail.MailConfig;
import com.mvc.config.ApplicationConfig;
import com.mvc.framework.util.DateUtils;
import com.mvc.portal.service.NotificationManager;
import com.mvc.security.model.User;
import com.mvc.security.service.UserManager;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-12-2
 */
@Service
public class TaskManager {

	private static final Logger	LOGGER	= Logger.getLogger(TaskManager.class);

	@Autowired
	private OrderManager	    orderManager;

	@Autowired
	private PurchaseManager	    purchaseManager;

	@Autowired
	private UserManager<User>	userManager;

	@Autowired
	private NotificationManager	notificationManager;

	@Autowired
	private ScheduleManager	    scheduleManager;

	public void runTask() {
		orderPayNotice();
		purchasePayNotice();
		closeDateNotice();
	}

	// Need pay before 5 days
	public void orderPayNotice() {
		Date noticeDate = DateUtils.getPreviousOrNextDaysOfNow(5);
		List<Order> orders = orderManager.getNeedPayOrder(DateUtils.getBeginOfTheDate(noticeDate));
		LOGGER.debug("total " + orders.size() + " orders need pay.");
		Map<String, String> messages = new HashMap<String, String>();
		while (orders.size() > 0) {
			User user = userManager.getByObjectId(orders.get(0).getSalesId());
			if (user != null) {
				StringBuilder message = new StringBuilder();
				List<Order> indexes = new ArrayList<Order>();
				for (Order order : orders) {
					if (order.getSalesId().equals(user.getObjectId())) {
						message.append(order.getOrderNo()).append(",");
						indexes.add(order);
					}
				}
				messages.put(user.getEmail() + ";" + user.getUserName(), indexes.size() + "个(" + message.substring(0, message.length() - 1)
				        + ")订单需要付款（5日内）.");
				for (Order order : indexes) {
					orders.remove(order);
				}
			}
		}
		sendMessages("需要付款的订单汇总", messages);
	}

	private void sendMessages(String subject, Map<String, String> messages) {
		if (subject == null) {
			subject = "";
		}
		String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String time = new SimpleDateFormat("yyyy年MM月dd日HH点").format(new Date());
		for (Iterator i = messages.entrySet().iterator(); i.hasNext();) {
			try {
				Map.Entry<String, String> e = (Map.Entry) i.next();
				MailConfig mailConifg = new MailConfig();
				mailConifg.setSubject(today + "日" + subject + "汇总");
				StringBuilder message = new StringBuilder(100);
				message.append(e.getKey().split(";")[1]).append(",您好:<br><div>" + ProjectUtils.getParagraphIndent() + "统计至").append(time)
				        .append(ApplicationConfig.getSystemName()).append("有").append(e.getValue())
				        .append("</div><br><div style='width:100%;text-align:right;margin-right:100px;'>")
				        .append(ApplicationConfig.getSystemName()).append("</div><br>").append(ProjectUtils.getCommonNoReplyMessage());
				notificationManager.sendMail(subject, message.toString(), new File[] {}, new String[] {},
				        new String[] { e.getKey().split(";")[0].trim() }, new String[] {}, false);
			} catch (Exception e) {
				LOGGER.error("sendMessages", e);
			}
		}
	}

	public void purchasePayNotice() {
		Date noticeDate = DateUtils.getPreviousOrNextDaysOfNow(5);
		List<Purchase> orders = purchaseManager.getNeedPayPurchase(DateUtils.getBeginOfTheDate(noticeDate));
		LOGGER.debug("total " + orders.size() + " purchases need pay.");
		Map<String, String> messages = new HashMap<String, String>();
		while (orders.size() > 0) {
			User user = userManager.getByObjectId(orders.get(0).getUserId());
			if (user != null) {
				StringBuilder message = new StringBuilder();
				List<Purchase> indexes = new ArrayList<Purchase>();
				for (Purchase order : orders) {
					if (order.getUserId().equals(user.getObjectId())) {
						message.append(order.getPurchaseNo()).append(",");
						indexes.add(order);
					}
				}
				messages.put(user.getEmail() + ";" + user.getUserName(), indexes.size() + "个(" + message.substring(0, message.length() - 1)
				        + ")采购单需要付款（5日内）.");
				for (Purchase order : indexes) {
					orders.remove(order);
				}
			}
		}
		sendMessages("需要付款的采购单汇总", messages);
	}

	public void closeDateNotice() {
		Date noticeDate = DateUtils.getPreviousOrNextDaysOfNow(5);
		List<Purchase> orders = purchaseManager.getNeedNoticePurchase(DateUtils.getBeginOfTheDate(noticeDate));
		LOGGER.debug("total " + orders.size() + " purchase need close.");
		Map<String, String> messages = new HashMap<String, String>();
		while (orders.size() > 0) {
			User user = userManager.getByObjectId(orders.get(0).getUserId());
			if (user != null) {
				StringBuilder message = new StringBuilder();
				List<Purchase> indexes = new ArrayList<Purchase>();
				for (Purchase order : orders) {
					if (order.getUserId().equals(user.getObjectId())) {
						message.append(order.getPurchaseNo()).append(",");
						indexes.add(order);
					}
				}
				messages.put(user.getEmail() + ";" + user.getUserName(), indexes.size() + "个(" + message.substring(0, message.length() - 1)
				        + ")的生产排期表的截仓时间已到（5日内）.");
				for (Purchase order : indexes) {
					orders.remove(order);
				}
			}
		}
		sendMessages("需要截仓的排期表汇总", messages);
	}

}
